import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'
import wx from "weixin-js-sdk";


/**
 * 判断是否在APP内
 */
const isApp = () => /hxsapp-version-/gi.test(window.navigator.userAgent)
/**
 * 是否上android，ios系列，取反即可
 */
const isAndroid = () => /android/gi.test(window.navigator.userAgent)
/**
 * 是否是微信环境
 */
const isWeChat = () => /micromessenger/gi.test(window.navigator.userAgent)
/**
 * 是否是微信小程序
 */
const isWeChatApp = () => {
  return new Promise((resolve, reject) => {
    let ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
      //微信环境下
      wx.miniProgram.getEnv(res => {
        if (res.miniprogram) {
          // 小程序环境下逻辑
          resolve(true)
          // return
        } else {
          resolve(false)
        }
      });
    } else {
      resolve(false)
    }
  })
}
/**
 * 是否iphoneX及以上
 */
const isIphonex = () =>
  /iphone/gi.test(window.navigator.userAgent) && window.screen.height >= 812
/**
 * url参数获取, Vue通过query也可以获取
 * @param {string} key 参数名字
 */
const getParamsFromUrl = (key = '') => {
  let search = window.location.search
  search = search.slice(1)

  let maps = search.split('&'),
    mapResult = {}

  forEach(maps, (keyValueProperty) => {
    let [key, value] = keyValueProperty.split('=')
    mapResult[key] = value
  })

  return isEmpty(key) ? mapResult : mapResult[key]
}

/**
 * @desc 页面初始化时  调用协议显示分享按钮
 * @param {String} shareTitle  分享标题
 * @param {String} shareLink  分享链接
 * @param {String} shareImages  封面地址
 * @param {String} shareDescr  分享描述
 * @param {String} shareType  文章类型id
 */
const initializationShare = ({
  shareTitle,
  shareLink,
  shareImages,
  shareDescr,
  shareType,
}) => {
  if (shareImages) {
    shareImages =
      shareImages.indexOf('?') > 0
        ? shareImages + '&x-oss-process=style/share'
        : shareImages + '?x-oss-process=style/share'
  }

  const _isApp = isApp()
  if (!_isApp) return
  window.location.href =
    'https://hxsapp_visible_share_btn#' +
    shareTitle +
    '#' +
    shareLink +
    '#' +
    shareImages +
    '#' +
    shareDescr +
    '#' +
    shareType
}

/**
 * @desc 页面初始化时  调用协议显示小程序分享按钮
 * @param {String} shareTitle  分享标题
 * @param {String} shareLink  分享链接
 * @param {String} shareImages  封面地址
 * @param {String} shareDescr  分享描述
 * @param {String} shareType  文章类型id
 */
const initShareStylea = ({
  shareTitle,
  shareLink,
  shareImages,
  shareDescr,
  shareType,
  shareWechatID,
  shareWechatPath,
  shareWechatType
}) => {
  if (shareImages) {
    shareImages =
      shareImages.indexOf('?') > 0
        ? shareImages + '&x-oss-process=style/share'
        : shareImages + '?x-oss-process=style/share'
  }

  const _isApp = isApp()
  if (!_isApp) return
  

  window.location.href =
    'https://hxsapp_act_share_stylea#' +
    shareTitle +
    '#' +
    shareLink +
    '#' +
    shareImages +
    '#' +
    shareDescr +
    '#' +
    shareType +
    '#' +
    shareWechatID+
    '#' +
    shareWechatPath +
    '#' +
    shareWechatType

}


/**
 * @descc js事件触发原生调起分享控件
 * @param {String} shareTitle  分享标题
 * @param {String} shareLink  分享链接
 * @param {String} shareImages  封面地址
 * @param {String} shareDescr  分享描述
 * @param {String} shareType  文章类型id
 * */
const jsShare = ({
  shareTitle,
  shareLink,
  shareImages,
  shareDescr,
  shareType,
}) => {
  /*shareImages =
    shareImages.indexOf('?') > 0
      ? shareImages + '&x-oss-process=style/share'
      : shareImages + '?x-oss-process=style/share'*/

  const isApp = /hxsapp-version-/gi.test(window.navigator.userAgent)
  if (!isApp) return
  window.location.href = `https://hxsapp_tune_up_share#${shareTitle}#${shareLink}#${shareImages}#${shareDescr}#0#${shareType}#0`
}

/**
 * 获取APP版本
 */
const getAppVersoin = () => {
  let userAgent = window.navigator.userAgent,
    __version = userAgent.split('hxsapp-version-')[1]
  let version = __version ? __version.split('&')[0] : '0.0.0'

  if (version.split('.').length === 1) version += '.0'
  return version
}

/**
 * 比较版本大小
 * @param {新版本} nVersion
 * @param {旧版本} oVersion
 */
const compareAppVersion = (nVersion, oVersion) => {
  nVersion = nVersion.split('.').length === 1 ? nVersion + '.0' : nVersion
  oVersion = oVersion.split('.').length === 1 ? oVersion + '.0' : oVersion
  return nVersion.replace(/\./g, '') > oVersion.replace(/\./g, '')
}

function padLeftZero (str) {
  return ('00' + str).substr(str.length)
}

/**
 * @desc 格式化时间
 * @param {Date} date 时间
 * @param {String} fmt 格式的模式 如: yyyy-MM-dd hh:mm:ss
 */
const formatDate = (date, fmt) => {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + ''
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      )
    }
  }
  return fmt
}

/**
 * @desc 将阿拉伯数字转为汉字
 * @param {num} num 阿拉伯数字
 */
const convertToChineseNumeral = (num) => {
  num = +num
  if (num == 10) {
    return '十'
  } else if (num == 1) {
    return '一'
  }
  const digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  const units = ['', '十', '百', '千', '万'];
  let result = '';
  let numStr = num.toString();
  for (let i = 0; i < numStr.length; i++) {
    let digit = parseInt(numStr.charAt(i));
    let unit = units[numStr.length - i - 1];
    if (digit === 0) {
      // 当前数字为0时不需要输出汉字，但需要考虑上一个数字是否为0，避免出现连续的零
      if (result.charAt(result.length - 1) !== '零') {
        result += '零';
      }
    } else {
      result += digits[digit] + unit;
    }
  }
  // 对于一些特殊的数字，如10、100等，需要在最前面加上“一”
  if (result.charAt(0) === '一') {
    result = result.substr(1, result.length);
  } else if (result.charAt(0) === '百') {
    result = '一' + result;
  } else if (result.charAt(0) === '千') {
    result = '一' + result;
  }
  return result
}

/**
 * @desc 链接参数拼接
 * @param {*} options
 * @param {*} url
 */
const splicingUrl = (options, url = '') => {
  const handleData = Object.keys(options).map(
    (item) => `${item}=${encodeURIComponent(options[item])}`
  )
  const _Url = handleData.length
    ? [url, url.indexOf('?') > -1 ? '&' : '?', handleData.join('&')].join('')
    : url

  return _Url
}
function getUrlParam (name, param = window.location.href.split('?')[1]) {
  if (!param) return null
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  var r = param.match(reg)
  if (r != null) return unescape(r[2])
  return null
}
function buildParams (params) {
  let query = "";
  for (let key in params) {
    if (params.hasOwnProperty(key)) {
      if (query !== "") {
        query += "&";
      }
      query += key + "=" + params[key];
    }
  }
  return query;
}
/**
 * @desc 配置深度链接库linkedme框架
 * @param {Object} __data linkedme 的个性化配置项
 * @return {String} 返回linkedme url链接
 */
const linkedMe = (__data = {}) => {
  __data.domText = __data.domText ? __data.domText : '下载APP'
  __data.domId = __data.domId ? __data.domId : 'LinkedMeDom'
  __data.domAId = __data.domAId ? __data.domAId : 'linkedMeOfA'
  // let __linkedme_key = "69aff539eac106c3ef597454a7c319ed";
  let __linkedme_key = 'e3c42293b7aabb3d838fd50478d079e0'

  // const ua = window.navigator.userAgent,
  //     isIos = new RegExp("iPhone", 'ig').test(ua),
  //     isplus = getUrlParam('isplus');
  // if( isIos && isplus ) __linkedme_key = 'e3c42293b7aabb3d838fd50478d079e0';

  const __type = process.env.NODE_ENV === 'production' ? 'live' : 'test'
  linkedme.init(__linkedme_key, { type: __type }, null)

  // 处理传入进来的参数
  var data = Object.assign({}, __data)
  data.type = __type //表示现在使用线上模式,如果填写"test", 表示测试模式.【可选】

  data.params = JSON.stringify(data.params)

  return new Promise((resolve, reject) => {
    linkedme.link(
      data,
      function (err, response) {
        if (err) {
          // 生成深度链接失败，返回错误对象err
          return 'error'
        } else {
          // 业务需要 直接跳转的情况
          if (__data.isOpenPage) {
            window.location.href = response.url
          } else if (document.getElementById(__data.domId)) {
            /*
            生成深度链接成功，深度链接可以通过data.url得到，
            将深度链接绑定到<a>标签，这样当用户点击这
            个深度链接，如果是在pc上，那么跳转到深度链接二维
            码页面，用户用手机扫描该二维码就会打开app；如果
            在移动端，深度链接直接会根据手机设备类型打开ios
            或者安卓app
            */
            document.getElementById(
              __data.domId
            ).innerHTML = `<a class="linkedme" id="${__data.domAId}" href="${response.url}">${__data.domText}</a>`
            document.getElementById(__data.domId).style.display = 'block'
          }
          resolve(response.url)
        }
      },
      false
    )
  })
}
// 获取App版本号
const getHxsAppVersion = () => {
  var UserAgent = window.navigator.userAgent
  var __version = UserAgent.split('hxsapp-version-')[1]
    ? UserAgent.split('hxsapp-version-')[1].split('&')[0]
    : '0.0.0'

  function __get_dian (str) {
    var num = 0
    for (var i = 0; i < str.length; i++) {
      if (str[i] === '.') {
        num++
      }
    }
    return num
  }

  // 先补零操作
  // 例如 2.10 ＝> 2.10.0
  // 例如 2.10.1 不会补零操作
  if (__get_dian(__version) === 1) {
    __version = __version + '.0'
  }
  return __version
}

//H5页面用户点击js事件调起分享商品-分享赚
const jsGoodsShare = ({
  shareTitle,
  shareLink,
  shareImages,
  shareDescr,
  shareType,
  goodsType,
}) => {
  const Version = getHxsAppVersion()
  if ((compareAppVersion(Version, '4.5.5') || Version === '4.5.5') && Version) {
    window.location.href = `https://hxsapp_tune_up_act_share#${shareTitle}#${shareLink}#${shareImages}#${shareDescr}#${shareType}#${goodsType}`
  } else {
    alert('请更新APP版本')
  }
}

const getUaData = (name) => {
  let _value = ''

  const UserAgent = window.navigator.userAgent

  const arr = UserAgent.split('&')

  if (!arr.length) return ''
  arr.forEach((item) => {
    if (item.indexOf(name) > -1) {
      // Toast(item)
      // _value = item.split('=')[1]
      const reg = new RegExp(name + '=')
      _value = item.replace(reg, '')
    }
  })

  return _value
}

const getREM = (size) => {
  let w = window.innerWidth
  return (w / 750) * size
}

export {
  isApp,
  isAndroid,
  isWeChat,
  isIphonex,
  getParamsFromUrl,
  getAppVersoin,
  compareAppVersion,
  getHxsAppVersion,
  initializationShare,
  jsShare,
  formatDate,
  convertToChineseNumeral,
  linkedMe,
  splicingUrl,
  jsGoodsShare,
  getUaData,
  getREM,
  isWeChatApp,
  buildParams,
  initShareStylea
}
